from flaskapp.exts import db


class PersonalBook(db.Model):
    __tablename__ = 'personalbooks'

    bookid = db.Column(db.Integer, primary_key=True)
    loanerid = db.Column(db.Integer, primary_key=True)
    bookname = db.Column(db.String(80), nullable=True)
    author = db.Column(db.String(80), nullable=False)
    press = db.Column(db.String(80), nullable=False)
    category = db.Column(db.String(80), nullable=True)
    coverpath = db.Column(db.String(80), nullable=True)
    surplus = db.Column(db.Integer, nullable=False)

    def __init__(self,loanerid, bookname, author, press, category, coverpath,surplus):
        self.bookname = bookname
        self.loanerid = loanerid
        self.author = author
        self.press = press
        self.surplus = surplus
        self.category = category
        self.coverpath = coverpath

    def __repr__(self):
        return f'<Book {self.loanerid} {self.bookname} {self.author} {self.press} {self.category} {self.coverpath}  {self.surplus}>'

    def to_dict(self):
        return {
            'bookid': self.bookid,
            'loanerid': self.loanerid,
            'bookname': self.bookname,
            'author': self.author,
            'press': self.press,
            'category': self.category,
            'coverpath': self.coverpath,
            'surplus': self.surplus
        }

    def update(self,loanerid, bookname, author, press, category, coverpath,surplus):
        self.loanerid = loanerid
        self.bookname = bookname
        self.author = author
        self.press = press
        self.surplus = surplus
        self.category = category
        self.coverpath = coverpath
        db.session.commit()

    def borrowPersonalBook(self):
        self.surplus -= 1
        if self.surplus < 0:
            return False
        else:
            db.session.add(self)
            db.session.commit()
            return True

    def returnBook(self):
        self.surplus += 1
        return True

    def addBook(self):
        db.session.add(self)
        db.session.commit()

    def deletePersonalBook(self):
        db.session.delete(self)
        db.session.commit()

    def addPsnlBook(self):
        db.session.add(self)
        db.session.commit()

